package com.laysonx.easy.invoke.core;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

public class ThymeleafViewResolverPostProcessor implements BeanPostProcessor, ApplicationContextAware {

    private static ApplicationContext context = null;

    @Override
    public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
        return o;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String s) throws BeansException {

        if (bean instanceof ThymeleafViewResolver) {
            SpringResourceTemplateResolver springResourceTemplateResolver = new SpringResourceTemplateResolver();
            springResourceTemplateResolver.setApplicationContext(context);
            springResourceTemplateResolver.setCacheable(true);
            springResourceTemplateResolver.setPrefix("classpath:/templates");
            springResourceTemplateResolver.setSuffix(".html");
            springResourceTemplateResolver.setTemplateMode("HTML");

            SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
            springTemplateEngine.setTemplateResolver(springResourceTemplateResolver);

            ((ThymeleafViewResolver) bean).setCharacterEncoding("UTF-8");
            ((ThymeleafViewResolver) bean).setTemplateEngine(springTemplateEngine);
            ((ThymeleafViewResolver) bean).setViewNames(new String[]{"/easy-invoke/*.html"});
            ((ThymeleafViewResolver) bean).setOrder(0);
            ((ThymeleafViewResolver) bean).setContentType("text/html");

        }
        return bean;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
}
